<?
class SiteTree
{
    var $pages;
	var $mainmenu;
	var $homepage;
	var $startpage;
	
	var $currentpage;
	var $currentpath;
	var $crumbs;
	var $params;
	
	
	function SiteTree($url='',$owner=1)	{
		$this->Read($url,$owner);
		}
	
	
	function Read($url='',$owner=1){
		$this->pages = array();
		$res=mysql_query("select * from pages where owner=$owner order by pos");
		while($page = mysql_fetch_assoc($res))
		{
			$this->pages[] = $page;
			if($page["mm"]) $this->mainmenu[] = $page;
			if($page["startpage"]) $this->startpage = $page;
			if($page["home"]) $this->homepage = $page;
		}
		if(!isset($this->homepage)) $this->homepage = $this->pages[0];
		if(!isset($this->startpage)) $this->startpage = $this->homepage;
		
		$this->crumbs = array();
		$urls = $this->parseURL($url);
		$urlcount=0;
		$parent=0;
		$urlmax=sizeof($urls);
		while($urlcount < $urlmax)
		{
			$node = $this->getPage($urls[$urlcount],$parent, true);
			if(!$node) break;
			$this->crumbs[] = $node;
			$this->currentpath .= '/'.$node['url'];
			$this->currentpage = $node;
			$parent = $node['id'];
			$urlcount++;
		}
		if($urlcount==0) 
		{
			$this->currentpath .= '/';
			$this->currentpage = $this->homepage;
		}
		$this->params=array_slice($urls,$urlcount);
		}
	
	function getPage($url,$parent,$onlyvisible=false)	{
		$sz = sizeof($this->pages);
		for($i=0; $i<$sz; $i++)
		{
			if($this->pages[$i]['parent'] == $parent && $this->pages[$i]['url'] == $url && (!$onlyvisible || $this->pages[$i]['visible'])) 
				return $this->pages[$i];
		}
		return false;
		}
	
	
	function getChilds($parent)	{
		$sz = sizeof($this->pages);
		$ret = array();
		for($i=0; $i<$sz; $i++)
		{
			if($this->pages[$i]['parent'] == $parent) 
				$ret[] = $this->pages[$i];
		}
		return $ret;
		}
	
	
	function hasChilds($id)	{
		$sz = sizeof($this->pages);
		for($i=0; $i<$sz; $i++)
		{
			if($this->pages[$i]['parent'] == $id) return true;
		}
		return false;
		}
	
	
	function parseURL($page=''){
		if(!$page)
			$page = substr($_SERVER["REQUEST_URI"],1);
		if(is_int(strpos($page,"?"))) 
			$page=substr($page,0,strpos($page,"?"));
		if(!$page) return Array();
		// delete last slash, if present
		if($page && $page[strlen($page)-1]=="/") $page=substr($page,0,strlen($page)-1);
		return explode('/',$page);
		}
	
	
	// admin interface functions:
	function Render() {
			$ret.='<li class="siteli">Сайт: <b>'.$_SERVER['HTTP_HOST'].'</b> <img src="images/newpage.gif" onclick="if(unloadPage2())newpage(0)" style="cursor:pointer;">'."\n";
			$ret.="<ul id='siteTree_1' class='treeview'>\n";
			
			$this->RenderRecursive($ret,0,false);
			
			$ret.="</ul></li>";
			return $ret;
		}
	
	
	function RenderRecursive(&$ret, $parent,$force_hidden)	{
			$pages = $this->getChilds($parent);
			
			foreach($pages as $page)
			{
				$img = 'file.gif';
				if($page['mm']) $img='mm.gif';
				if($page['home']) $img='home.gif';
				if($page['visible']==0) $img='hidden.gif';
				if($force_hidden) $img='hidden.gif';
				$ret.='<li class="sortables" id="'.$page['id'].'"><div id="cdiv'.$page['id'].'" oncontextmenu="context(event,\''.$page['id'].'\',this,\''.$page['title'].'\');return false;" unselectable=on><img class="dr" src="images/'.$img.'" alt=""><a href="" onclick="context(event,\''.$page['id'].'\',\'cdiv'.$page['id'].'\',\''.$page['title'].'\');return false;">'.$page['title'].'</a>&nbsp;&nbsp;&nbsp;<img src="images/editpage.gif" onclick="if(unloadPage2())editpage('.$page['id'].')" class="hide"><img src="images/newpage.gif" onclick="if(unloadPage2())newpage('.$page['id'].')" class="hide"><img src="images/delpage.gif" onclick="delpage('.$page['id'].',\''.$page['title'].'\')"  class="hide"></div>'."\n";
				if($this->hasChilds($page["id"])) 
				{
					$old_force_hidden = $force_hidden;
					if($page['visible']==0) $force_hidden=true;
					$ret.="<ul>";
					$this->RenderRecursive($ret,$page['id'],$force_hidden);
					$ret.="</ul>";
					$force_hidden = $old_force_hidden;
				}
				$ret.="</li>";
			}
		}
	
	
	function Get($what,$site=0)	{
		if($what=="pages") return $this->pages;
		if($what=="mainmenu") return $this->mainmenu;
		if($what=="homepage") return $this->homepage;
		if($what=="startpage") return $this->startpage;
		}
	
	
	function UpdateTree($qs) {
		// удаление и упорядочивание
		$newtree=array();
		$qss = explode("\n",$qs);
		$lastid=0;
		$pos=0;
		$stack=array(0);
		$cnt=sizeof($qss);
		for($i=0;$i<$cnt;$i++) { if($qss[$i]) {
			$key=array_pop($stack);
			list($offset,$pageid) = explode(':',$qss[$i]);
			$newtree['p'.$pageid] = array('parent'=>$key,'pos'=>$pos++);
			array_push($stack,$key);
			if($i+1<$cnt){
				list($nextoffset,$nextpageid) = explode(':',$qss[$i+1]);
				if($nextoffset>$offset) array_push($stack,$pageid);
				while($nextoffset<$offset) {array_pop($stack);$offset--;}
				}
			}}
			
		$res = mysql_query("select * from pages");
		while($row=mysql_fetch_assoc($res)){
			if($newtree['p'.$row['id']]) 
				mysql_query('update pages set parent='.$newtree['p'.$row['id']]['parent'].', pos='.$newtree['p'.$row['id']]['pos'].' where id='.$row['id']);
			else {
				mysql_query('delete from pages where id='.$row['id']);
				mysql_query('delete from page_content where pageid='.$row['id']);
				}
			}
		$this->UpdateFullpath();
		$this->Read();
	}
	
	function UpdateFullpath($parent=0,$path='') {
		// рекурсиваная функция.
		// проходим по дереву и обновляем страницам поле Fullpath
		$pagelist = DBGetRows("select id,url from pages where parent=$parent");
		foreach($pagelist as $row){
			$newpath=$path.$row['url'];
			mysql_query("update pages set fullpath='$newpath' where id=".$row['id']);
			$this->UpdateFullpath($row['id'],$newpath.'/');
			}
		}
	
	function Add()	{
		$newpos=$this->GetMaxPosFor($_REQUEST['parent']);
		if($_REQUEST['home']) mysql_query('update pages set home=0');
		if($_REQUEST['startpage']) mysql_query('update pages set startpage=0');
		
		mysql_query("insert into pages (title,url,maket,parent,pagetype,mm,startpage,home,pos,visible,keywords) values ('{$_REQUEST[title]}','{$_REQUEST[url]}','{$_REQUEST[maket]}','{$_REQUEST[parent]}',$_REQUEST[pagetype],'".($_REQUEST['mm']?1:0)."','".($_REQUEST['startpage']?1:0)."','".($_REQUEST['home']?1:0)."',{$newpos},".($_REQUEST['visible']?1:0).",'{$_REQUEST[keywords]}')");
		$newid = mysql_insert_id();
		mysql_query("insert into page_content (pageid,content) values ($newid,'".($_REQUEST['pagetype']==0?mysql_real_escape_string($_REQUEST['tex']):mysql_real_escape_string($_REQUEST['template']))."')");
		
		$this->UpdateFullpath();
		ClearGet('structure.php');
		}
	
	function Update()	{
		if($_REQUEST['home']) mysql_query('update pages set home=0');
		if($_REQUEST['startpage']) mysql_query('update pages set startpage=0');
		mysql_query("update pages set title='{$_REQUEST[title]}',keywords='{$_REQUEST[keywords]}',url='{$_REQUEST[url]}',maket='{$_REQUEST[maket]}',pagetype=$_REQUEST[pagetype],mm=".($_REQUEST['mm']?1:0).",startpage=".($_REQUEST['startpage']?1:0).",home=".($_REQUEST['home']?1:0).",visible=".($_REQUEST['visible']?1:0)." where id=".$_REQUEST['id']);
		mysql_query("delete from page_content where pageid=".$_REQUEST['id'] );
		mysql_query("insert into page_content (pageid,content) values ({$_REQUEST[id]},'".($_REQUEST['pagetype']==0?mysql_real_escape_string($_REQUEST['tex']):mysql_real_escape_string($_REQUEST['template']))."')");
		
		$this->UpdateFullpath();
		ClearGet('structure.php');
		}
	
	function GetMaxPosFor($parent)	{
		$max=0;
		$childs = $this->getChilds($parent);
		foreach($childs as $child) if($child['pos']>$max) $max=$child['pos'];
		return ($max+1);
		}
}

/*
class SiteTree
{
	var $currentpage;
	var $currentpath;
	var $params;
	var $crumbs;
	
	var $pages;
	var $mainmenu;
	
	function SiteTree($url=''){
		$this->Read($url);
		}
	
	
	function loadTreeRecursive($parent=0){
		$res=mysql_query("select * from pages where parent=$parent order by pos");
		while($row=mysql_fetch_assoc($res)) {
			// смотрим, является ли данная страница частью текущего пути
			//if($urlcount<$urlmax && $urls[$urlcount]==$row['url'] && $row['parent']==$urlpoint && $row['visible']==1){
			//	$urlcount++;
			//	$urlpoint=$row['id'];
			//	$this->crumbs[]=Array('url'=>$row['url'],'title'=>$row['title']);
			//	$this->currentpath.='/'.$row['url'];
			//	$this->currentpage=$row;
			//	}
			if(!$newpages[$row['parent']]) $newpages[$row['parent']]=Array();
			$newpages[$row['parent']][]=$row; 
			if($row["mm"] && $row["visible"]) $mainmenu[]=$row;
			if($row["home"]) $homepage=$row;
			if($row["startpage"]) $startpage=$row;
			if(!$homepage && $row["visible"]) $homepage=$row;
			}
		}
	
	
	function Read($url=''){
		$this->pages = Array();
		$this->mainmenu = Array();
		$this->crumbs=Array();
		
		$urls = $this->CurrentURL($url);
		$urlpoint=0;
		$urlcount=0;
		$urlmax=sizeof($urls);
		
		$res=mysql_query("select * from pages order by pos");
		$newpages=array();
		$mainmenu=array();
		while($row=mysql_fetch_assoc($res)) {
			// смотрим, является ли данная страница частью текущего пути
			if($urlcount<$urlmax && $urls[$urlcount]==$row['url'] && $row['parent']==$urlpoint && $row['visible']==1){
				$urlcount++;
				$urlpoint=$row['id'];
				$this->crumbs[]=Array('url'=>$row['url'],'title'=>$row['title']);
				$this->currentpath.='/'.$row['url'];
				$this->currentpage=$row;
				}
			if(!$newpages[$row['parent']]) $newpages[$row['parent']]=Array();
			$newpages[$row['parent']][]=$row;
			if($row["mm"] && $row["visible"]) $mainmenu[]=$row;
			if($row["home"]) $homepage=$row;
			if($row["startpage"]) $startpage=$row;
			if(!$homepage && $row["visible"]) $homepage=$row;
			}
		
		if(!$startpage) $startpage=$homepage;
		if(!$homepage) $homepage=$startpage;
    	if(!$this->currentpage) $this->currentpage = $startpage;
		if(!$this->currentpage['keywords']) $this->currentpage['keywords'] = $homepage['keywords'];
		$this->params=array_slice($urls,$urlcount);
		
		$this->sites[]=Array('pages'=>$newpages,'mm'=>$mainmenu,'home'=>$homepage,'startpage'=>$startpage,'title'=>'default','lang'=>'0');
		}
	
	
	
	function Get($what,$site=0)	{
		return $this->sites[$site][$what];
		}
	
	
	
	
	function CurrentURL($page=''){
		if(!$page)
			$page = substr($_SERVER["REQUEST_URI"],1);
		if(is_int(strpos($page,"?"))) 
			$page=substr($page,0,strpos($page,"?"));
		if(!$page) return Array();
		// delete last slash, if present
		if($page && $page[strlen($page)-1]=="/") $page=substr($page,0,strlen($page)-1);
		return explode('/',$page);
		}
	
	
	
	
	
	
	
	
	
	
	
	
	function Render() {
		foreach($this->sites as $site){
			$ret.='<li class="siteli">Сайт: <b>'.$site['title'].'</b> <img src="images/newpage.gif" onclick="if(unloadPage2())newpage(0)" style="cursor:pointer;">'."\n";
			$ret.="<ul id='siteTree_{$site[title]}' class='treeview'>\n";
			$ll=0;
			$hidden_childs=0;
			
			$stack=array(0);
			while($stack)
			{
				$key=array_pop($stack);
				$page=current($site['pages'][$key]);
				if($page){
					$img = 'file.gif';
					if($page['mm']) $img='mm.gif';
					if($page['home']) $img='home.gif';
					if($page['visible']==0) $img='hidden.gif';
					if($hidden_childs) $img='hidden.gif';
					$ret.='<li class="sortables" id="'.$page['id'].'"><div id="cdiv'.$page['id'].'" oncontextmenu="context(event,\''.$page['id'].'\',this,\''.$page['title'].'\');return false;" unselectable=on><img class="dr" src="images/'.$img.'" alt=""><a href="" onclick="context(event,\''.$page['id'].'\',\'cdiv'.$page['id'].'\',\''.$page['title'].'\');return false;">'.$page['title'].'</a>&nbsp;&nbsp;&nbsp;<img src="images/editpage.gif" onclick="if(unloadPage2())editpage('.$page['id'].')" class="hide"><img src="images/newpage.gif" onclick="if(unloadPage2())newpage('.$page['id'].')" class="hide"><img src="images/delpage.gif" onclick="delpage('.$page['id'].',\''.$page['title'].'\')"  class="hide"></div>'."\n";
					array_push($stack, $key);
					if(isset($site['pages'][$page['id']])){
						if($page['visible']==0) $hidden_childs=sizeof($stack);
						array_push($stack, $page['id']);
						$ret.="<ul>";
						}
					$ret.="";
					next($site['pages'][$key]);
					}
				else $ret.="</li></ul>";
				if(sizeof($stack)<$hidden_childs+1) $hidden_childs=0;
				}
			}
		return $ret;
		}
	
	
	
	function UpdateTree($qs) {
		// удаление и упорядочивание
		$newtree=array();
		$qss = explode("\n",$qs);
		$lastid=0;
		$pos=0;
		$stack=array(0);
		$cnt=sizeof($qss);
		for($i=0;$i<$cnt;$i++) { if($qss[$i]) {
			$key=array_pop($stack);
			list($offset,$pageid) = explode(':',$qss[$i]);
			$newtree['p'.$pageid] = array('parent'=>$key,'pos'=>$pos++);
			array_push($stack,$key);
			if($i+1<$cnt){
				list($nextoffset,$nextpageid) = explode(':',$qss[$i+1]);
				if($nextoffset>$offset) array_push($stack,$pageid);
				while($nextoffset<$offset) {array_pop($stack);$offset--;}
				}
			}}
			
		$res = mysql_query("select * from pages");
		while($row=mysql_fetch_assoc($res)){
			if($newtree['p'.$row['id']]) 
				mysql_query('update pages set parent='.$newtree['p'.$row['id']]['parent'].', pos='.$newtree['p'.$row['id']]['pos'].' where id='.$row['id']);
			else {
				mysql_query('delete from pages where id='.$row['id']);
				mysql_query('delete from page_content where pageid='.$row['id']);
				}
			}
		$this->UpdateFullpath();
		$this->Read();
	}
	
	
	
	
	
	
	
	
	
	function Add()	{
		$newpos=$this->GetMaxPosFor($_REQUEST['parent']);
		if($_REQUEST['home']) mysql_query('update pages set home=0');
		if($_REQUEST['startpage']) mysql_query('update pages set startpage=0');
		
		mysql_query("insert into pages (title,url,maket,parent,pagetype,mm,startpage,home,pos,visible,keywords) values ('{$_REQUEST[title]}','{$_REQUEST[url]}','{$_REQUEST[maket]}','{$_REQUEST[parent]}',$_REQUEST[pagetype],'".($_REQUEST['mm']?1:0)."','".($_REQUEST['startpage']?1:0)."','".($_REQUEST['home']?1:0)."',{$newpos},".($_REQUEST['visible']?1:0).",'{$_REQUEST[keywords]}')");
		$newid = mysql_insert_id();
		mysql_query("insert into page_content (pageid,content) values ($newid,'".($_REQUEST['pagetype']==0?mysql_real_escape_string($_REQUEST['tex']):mysql_real_escape_string($_REQUEST['template']))."')");
		
		$this->UpdateFullpath();
		ClearGet('structure.php');
	}
	
	function Update()	{
		if($_REQUEST['home']) mysql_query('update pages set home=0');
		if($_REQUEST['startpage']) mysql_query('update pages set startpage=0');
		mysql_query("update pages set title='{$_REQUEST[title]}',keywords='{$_REQUEST[keywords]}',url='{$_REQUEST[url]}',maket='{$_REQUEST[maket]}',pagetype=$_REQUEST[pagetype],mm=".($_REQUEST['mm']?1:0).",startpage=".($_REQUEST['startpage']?1:0).",home=".($_REQUEST['home']?1:0).",visible=".($_REQUEST['visible']?1:0)." where id=".$_REQUEST['id']);
		mysql_query("delete from page_content where pageid=".$_REQUEST['id'] );
		mysql_query("insert into page_content (pageid,content) values ({$_REQUEST[id]},'".($_REQUEST['pagetype']==0?mysql_real_escape_string($_REQUEST['tex']):mysql_real_escape_string($_REQUEST['template']))."')");
		
		$this->UpdateFullpath();
		ClearGet('structure.php');
	}
	
	
	
	function UpdateFullpath($parent=0,$path='') {
		// рекурсиваная функция.
		// проходим по дереву и обновляем страницам поле Fullpath
		$pagelist = DBGetRows("select id,url from pages where parent=$parent");
		foreach($pagelist as $row){
			$newpath=$path.$row['url'];
			mysql_query("update pages set fullpath='$newpath' where id=".$row['id']);
			$this->UpdateFullpath($row['id'],$newpath.'/');
			}
		}
	
	
	
	function GetMaxPosFor($parent,$owner=1,$lang=0)	{
		$max=0;
		$cnt=count($this->sites[0]['pages'][$parent]);
		for($i=0;$i<$cnt;$i++) if($this->sites[0]['pages'][$parent][$i]['pos']>$max) $max=$this->sites[0]['pages'][$parent][$i]['pos'];
		return ($max+1);
		}
}*/